/*
    Copyright (C) 2008-2009 Dmitry Gusev <dmitry.gusev@gmail.com>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

 */

package dmitrygusev.web4konverta.mobile;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

/**
 *
 * @author dmitrygusev
 */
public class PingAction {

    private Application app;
    private static final String pingURL =
            "http://weandtech.ru/dmitrygusev/analytics/visit.php";

    public PingAction(Application app) {
        this.app = app;
    }

    public boolean execute() {
        HttpConnection conn = null;
        try {
            conn = (HttpConnection) Connector.open(pingURL);

            String msg = "visitor=" + Utils.encode(
                            app.getAppConfig().getAccountName().toLowerCase()).hashCode()
                       + "&screen_size=" + app.getScreenSize()
                       + "&client_datetime=" + Utils.encode(
                            Utils.formatAsMySQLDatetime(new Date()))
                       + "&action=ping"
                       + "&platform_id=" + Utils.encode(app.getPlatformName())
                       + "&app_id=" + app.getVersion();

            conn.setRequestMethod(HttpConnection.POST);

            conn.setRequestProperty("Content-Length", "" + msg.length());
            conn.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            OutputStream os = conn.openOutputStream();
            os.write(msg.getBytes());
            os.close();

            int rc = conn.getResponseCode();

            return rc == HttpConnection.HTTP_OK;
        } catch (Exception ex) {

        } finally {
            if (conn != null) {
                try { conn.close(); } catch (IOException e) {}
                conn = null;
            }
        }

        return false;
    }

}